package com.chen;


import com.chen.util.DistributeLockUtil;
import com.chen.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.util.stream.IntStream;

@SpringBootApplication
@Slf4j
public class Application {
    @Autowired
    private DistributeLockUtil distributeLockUtil;

    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }

    @Bean
    public void distributeLockTest(){
        IntStream.range(0,3).forEach(i->{
            new Thread(()->{
                //获取锁
                String lockValue = null;
                try {
                    while ((lockValue = distributeLockUtil.getLock())==null){
                        Thread.sleep(200);
                    }
                    log.info("线程"+Thread.currentThread().getName()+"获取到锁，锁的值为："+lockValue);
                    //休眠2秒，模拟业务执行
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //业务执行结束，释放锁
                if (distributeLockUtil.releaseLock(lockValue)){
                    log.info("线程"+Thread.currentThread().getName()+"成功释放分布式锁："+lockValue);
                }
            }).start();
        });

    }
}
